<?php

namespace app\mp\admin;

use app\system\admin\Admin;
use app\common\model\Depart as DepartModel;
use think\Db;
use think\db\Where;

class Depart extends Admin
{
    protected $hisiModel = 'Depart';//模型名称[通用添加、修改专用]
    protected $hisiValidate = 'Depart';
    protected $hisiAddScene = '';//添加数据验证场景名
    protected $hisiEditScene = '';//更新数据验证场景名

    public function initialize()
    {
        parent::initialize();
    }

    public function index()
    {
        if ($this->request->isAjax()) {
            $where = $data = [];
            $page = $this->request->param('page/d', 1);
            $limit = $this->request->param('limit/d', 20);
            $keyword = $this->request->param('keyword/s');

            $where[]    = ['d.status', 'eq', 1];
            if ($keyword) {
                $where[] = ['d.name', 'like', "%{$keyword}%"];
            }

            $order = 'd.id desc';
            $list = DepartModel::alias('d')
                ->field('d.*,ifnull(f.name, "") as factory_name')
                ->where($where)
                ->join('factory f', 'f.id=d.factory_id', 'left')
                ->page($page)
                ->limit($limit)
                ->order($order)
                ->select();
            $data['count'] = DepartModel::alias('d')->where($where)->count();
            $list = empty($list) ? [] : $list->toArray();
            $data['data'] = $list;
            $data['code'] = 0;
            $data['msg'] = '';
            return json($data);
        }

        $assign = [];
        return $this->assign($assign)->fetch();
    }

    /**
     * [通用方法]添加页面展示和保存
     * @return mixed
     * @author 橘子俊 <364666827@qq.com>
     */
    public function add()
    {
        if ($this->request->isPost()) {

            $postData = $this->request->post();

            if ($this->hisiValidate) {// 数据验证

                if (strpos($this->hisiValidate, '\\') === false) {

                    if (defined('IS_PLUGINS')) {
                        $this->hisiValidate = 'plugins\\' . $this->request->param('_p') . '\\validate\\' . $this->hisiValidate;
                    } else {
                        $this->hisiValidate = 'app\\' . $this->request->module() . '\\validate\\' . $this->hisiValidate;
                    }

                }

                if ($this->hisiAddScene) {
                    $this->hisiValidate = $this->hisiValidate . '.' . $this->hisiAddScene;
                }

                $result = $this->validate($postData, $this->hisiValidate);
                if ($result !== true) {
                    return $this->error($result);
                }

            }

            if ($this->hisiModel) {// 通过Model添加

                $model = $this->model();

                if (!$model->save($postData)) {
                    return $this->error($model->getError());
                }

            } else if ($this->hisiTable) {// 通过Db添加

                if (!Db::name($this->hisiTable)->insert($postData)) {
                    return $this->error('保存失败');
                }

            } else {

                return $this->error('当前控制器缺少属性（hisiModel、hisiTable至少定义一个）');

            }

            return $this->success('保存成功', '');
        }

        $template = $this->request->param('template', 'form');
        $factoryList = ['0' => '请选择'] + getFactoryKV();

        return $this->assign('factoryList', $factoryList)->fetch($template);
    }

    /**
     * [通用方法]编辑页面展示和保存
     * @author 橘子俊 <364666827@qq.com>
     * @return mixed
     */
    public function edit()
    {
        if ($this->request->isPost()) {// 数据验证

            $postData = $this->request->post();

            if ($this->hisiValidate) {

                if (strpos($this->hisiValidate, '\\') === false ) {

                    if (defined('IS_PLUGINS')) {
                        $this->hisiValidate = 'plugins\\'.$this->request->param('_p').'\\validate\\'.$this->hisiValidate;
                    } else {
                        $this->hisiValidate = 'app\\'.$this->request->module().'\\validate\\'.$this->hisiValidate;
                    }

                }

                if ($this->hisiEditScene) {
                    $this->hisiValidate = $this->hisiValidate.'.'.$this->hisiEditScene;
                }

                $result = $this->validate($postData, $this->hisiValidate);
                if ($result !== true) {
                    return $this->error($result);
                }

            }
        }

        $where = [];
        if ($this->hisiModel) {// 通过Model更新

            $model = $this->model();

            $pk = $model->getPk();
            $id = $this->request->param($pk);

            $where[]= [$pk, '=', $id];
            $where  = $this->getRightWhere($where);

            if ($this->request->isPost()) {

                if ($model->save($postData, $where) === false) {
                    return $this->error($model->getError());
                }

                return $this->success('保存成功', '');
            }

            $formData = $model->where($where)->find();

        } else if ($this->hisiTable) {// 通过Db更新

            $db = Db::name($this->hisiTable);
            $pk = $db->getPk();
            $id = $this->request->param($pk);

            $where[]= [$pk, '=', $id];
            $where  = $this->getRightWhere($where);

            if ($this->request->isPost()) {

                if (!$db->where($where)->update($postData)) {
                    return $this->error('保存失败');
                }

                return $this->success('保存成功', '');
            }

            $formData = $db->where($where)->find();

        } else {

            return $this->error('当前控制器缺少属性（hisiModel、hisiTable至少定义一个）');

        }

        if (!$formData) {
            return $this->error('数据不存在或没有权限');
        }

        $this->assign('formData', $formData);

        $template = $this->request->param('template', 'form');

        $factoryList = ['0' => '请选择'] + getFactoryKV();
        return $this->assign('factoryList', $factoryList)->fetch($template);
    }

}